package com.dmagic.cms.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dmagic.cms.common.annotation.FormModel;
import com.dmagic.cms.common.annotation.RequestJsonParam;
import com.dmagic.cms.common.controller.CommonController;
import com.dmagic.cms.common.query.ConditionsBean;
import com.dmagic.cms.common.query.PageUtil;
import com.dmagic.cms.common.util.HibernateUtils;
import com.dmagic.cms.common.util.JsonUtil;
import com.dmagic.cms.common.util.ListUtil;
import com.dmagic.cms.common.util.NumberUtil;
import com.dmagic.cms.common.util.StringUtil;
import com.dmagic.cms.entity.AppUser;
import com.dmagic.cms.entity.Permission;
import com.dmagic.cms.service.AppUserService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

@Controller
@RequestMapping(value = "/user")
public class AppUserController extends CommonController {

	private String USER_ADD = "user/userAdd";

	private String USER_LIST = "user/userList";
	static {

	}

	@Autowired
	private AppUserService userService;

	@RequestMapping()
	public String list() {
		return USER_LIST;
	}

	@RequestMapping(value = "search", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String search(@RequestParam Integer pageNo, @RequestParam Integer pageSize,
			@RequestParam String orderType, @RequestParam String orderBy,
			@RequestJsonParam("rules") List<ConditionsBean> conditions) {
		PageUtil<AppUser> pageUtil = new PageUtil<AppUser>();
		pageUtil.setAutoCount(true);
		pageUtil.setPageNo(pageNo);
		pageUtil.setPageSize(pageSize);
		pageUtil.setOrder(orderType);
		pageUtil.setOrderBy(orderBy);
		pageUtil.setConditions(conditions);
		userService.searchAppUser(pageUtil);
		return JsonUtil.toFullJson(pageUtil);
	}

	@RequestMapping("edit/{userId}")
	public String edit(@PathVariable("userId") Long userId, Model model) {
		AppUser user = getUser(userId);
		model.addAttribute("permissions", userService.getAllPermissions());
		model.addAttribute("user", user);
		model.addAttribute("mode", "update");
		return USER_ADD;
	}

	@ModelAttribute("user")
	public AppUser getUser(Long userId) {
		if (userId == null) {
			return new AppUser();
		}
		return userService.getAppUserByUserId(userId);
	}

	@RequestMapping("add")
	public String add(Model model) {
		List<Permission> permissions = userService.getAllPermissions();
		model.addAttribute("permissions", permissions);
		model.addAttribute("user", new AppUser());
		model.addAttribute("mode", "save");
		return USER_ADD;
	}

	@RequestMapping("save")
	public String save(@ModelAttribute("user") AppUser user,
			@RequestParam(value = "permissions") List<Long> permissionIds,
			RedirectAttributes redirectAttributes) {
		// 根据页面上的checkbox选择 整合User的Roles Set
		if (ListUtil.isEmpty(user.getPermissions())) {
			List<Permission> permissionList = Lists.newArrayList();
			/*
			 * for (Long permissionId : permissionIds) { Permission p = new
			 * Permission(); p.setPermissionId(permissionId);
			 * permissionList.add(p); }
			 */
			user.setPermissions(permissionList);
		}
		try {
			HibernateUtils.mergeByCheckedIds(user.getPermissions(), permissionIds, Permission.class);
			userService.saveAppUser(user);
			redirectAttributes.addFlashAttribute(SUCCESS, "Save Successful.");
		} catch (Exception e) {
			redirectAttributes.addFlashAttribute(ERROR, e.getMessage());
		}
		return "redirect:/user.do";
	}

	@RequestMapping("delete")
	@ResponseBody
	public String delete(@RequestJsonParam("userIds") List<Long> userIds) {
		userService.deleteUser(userIds);
		return "Delete Successful.";
	}

	@RequestMapping("delete/{userId}")
	@ResponseBody
	public String delete(@PathVariable("userId") Long userId) {
		try {
			userService.deleteUserById(userId);
		} catch (Exception e) {
			return e.getMessage();
		}
		return "Delete Successful.";
	}

	@RequestMapping(value = "checkName")
	@ResponseBody
	public String checkName(@RequestParam("oldName") String oldName, @RequestParam("userName") String userName)
			throws Exception {
		if (StringUtil.equals(oldName, userName)) {
			return "true";
		} else if (userService.getAppUserByUserName(userName) == null) {
			return "true";
		}

		return "false";
	}

	/**
	 * 不自动绑定对象中的roleList属性，另行处理。
	 */
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.setDisallowedFields("permissions");
	}
}
